/******************************************************
 Project:				PCSync
 Author:				Jean-Philippe
 File name:				ConfigLoader.java
 Date created:			2012-08-17
 Date last modified:	2012-08-17
 *******************************************************
 Modification History
 *******************************************************
 2012-08-17		Initial version.
 ******************************************************/
package pcsync.client;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Iterator;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

/**
 * @author Jean-Philippe
 *
 */
public class DirectoryLoader implements Iterable<Path>
{
	private static final String LOGGER_PROPERTIES_FILE = "cfg/logging.properties"; 
	
	private Logger logger;
	private ArrayList<Path> directories;
	
	public DirectoryLoader(String directoriesConfigFile)
	{
		// Enable logging
		PropertyConfigurator.configure(LOGGER_PROPERTIES_FILE);
		logger = Logger.getLogger(this.getClass().getCanonicalName());
		
		this.directories = new ArrayList<Path>();
		this.loadFromFile(directoriesConfigFile);
		
		logger.info("Done");
	}
	
	private boolean loadFromFile(String strFile)
	{
		try
		{
			// Open the file
			logger.info("Reading configuration file " + strFile);
			FileInputStream fstream = new FileInputStream(strFile);
			
			// Get the object of DataInputStream
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;
			
			//Read File Line By Line
			while ((strLine = br.readLine()) != null) {
				
				Path path = FileSystems.getDefault().getPath(strLine);
				
				if( path.toFile().exists() )
				{
					if( path.toFile().isDirectory() )
					{
						this.directories.add(path);
						Files.walkFileTree(path, new FileLoader());
					}
					else
					{
						logger.info("Directory to track: " + strLine);
						logger.warn("Path '" + path.toString() + "' is not a directory.");
					}
				}
				else
				{
					logger.warn("Directory '" + path.toString() + "' does not exist.");
				}
					
			}
			
			//Close the input stream
			in.close();
		}
		catch (Exception e)
		{
			//Catch exception if any
			System.err.println("Error: " + e.getMessage());
			logger.error("Unable to load config file \""+strFile+"\"");
			return false;
		}
		
		return true;
	}
	
	public static void main(String[] args)
	{
		new DirectoryLoader("cfg/directories.conf");
	}
	
	@Override
	public Iterator<Path> iterator()
	{
		return this.directories.iterator();
	}
}